package com.yc.service.xcx.user.impl;


import javax.annotation.Resource;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.yc.dao.DaoSupport;
import com.yc.service.system.doctor.IDoctorManager;
import com.yc.service.system.user.UserManager;
import com.yc.service.xcx.XCXConfig;
import com.yc.service.xcx.XCXConst;
import com.yc.service.xcx.base.XCXBaseService;
import com.yc.service.xcx.user.INormalUser;
import com.yc.service.xcx.user.ISessionManagerService;
import com.yc.service.xcx.user.IXCXUserService;
import com.yc.util.MD5Util;
import com.yc.util.PageData;
import com.yc.util.ReturnModel;
import com.yc.util.UuidUtil;

@Service
public class XCXUserService extends XCXBaseService implements IXCXUserService {

	@Resource(name = "daoSupport")
	private DaoSupport dao;

	@Resource(name = "xcxConfig")
	private XCXConfig xcxConfig;
	

	// 会话管理
	@Resource
	private ISessionManagerService sessionManagerService;

	@Resource
	private IDoctorManager doctorManager;

	// 普通小程序用户
	@Resource
	private INormalUser normalUser;

	// 后台用户
	@Resource(name = "userService")
	private UserManager userService;

	@Override
	public ReturnModel getAccessToken(String code) {
		// TODO Auto-generated method stub

		ReturnModel returnModel = new ReturnModel();
		String url = XCXConst.CODE_GET_SESSION_KEY.replace("{appid}", xcxConfig.getXcxappid())
				.replace("{secret}", xcxConfig.getXcxappSecret()).replace("{js_code}", code);

		try {
			String jsonStr = this.requestGetJson(url);
			JSONObject obj = JSONObject.parseObject(jsonStr);
			if (obj.get("errcode") == null) {

				String sessionkey = obj.getString("session_key");
				String openid = obj.getString("openid");
				// Integer expires_in = obj.getInteger("expires_in");

				String accessToken = Base64.encode(MD5Util
						.md5Encode(System.currentTimeMillis() + openid + sessionkey + String.valueOf(Math.random()),
								null)
						.getBytes());
				PageData pd1 = new PageData();
				pd1.put("3TDSESSION", accessToken);
				pd1.put("OPENID", openid);
				pd1.put("SESSION_KEY", sessionkey);

				PageData session = sessionManagerService.findByOpenId(pd1);
				if (session == null || session.get("3TDSESSION") == null) {
					sessionManagerService.save(pd1);
				} else {
					
					// 更新会话及有效时间
					sessionManagerService.edit(pd1);
				}

				PageData pd = new PageData();
				pd.put("OPENID", openid);
				pd.put("PASSWORD", openid);
				pd.put("USERTYPE", "0");
				String usertype = "0";
				PageData result = this.findById(pd);
				if (result == null || result.size() == 0) {
					this.save(pd); // 插入用户

					PageData normal = new PageData();
				    returnModel.setResult(true);
					normal.put("usertype", "0");
					normal.put("AccessToken", accessToken);
					returnModel.setDatum(normal);
					return returnModel;
					
					
				} else {
					 usertype = result.getString("USERTYPE");
					 
					 if("1".equals(usertype)){ //小程序用户，看看用户是否被禁用
						PageData normal =  normalUser.findById(pd);
						String rcdsts = normal.getString("RCDSTS");
						if("D".equalsIgnoreCase(rcdsts)){
							returnModel.setResult(false);
							returnModel.setReason("用户已禁用，请联系医创频道！");
							returnModel.setDatum(null);
							return returnModel;
						} else {
							returnModel.setResult(true);
							normal.put("usertype", usertype);
							normal.put("AccessToken", accessToken);
							returnModel.setDatum(normal);
							return returnModel;
						}
					 } else if("2".equals(usertype)){
						 
						 PageData normal =  doctorManager.findByOpenId(pd);
						 returnModel.setResult(true);
							normal.put("usertype", usertype);
							normal.put("AccessToken", accessToken);
							returnModel.setDatum(normal);
							return returnModel;
						 
					 }
				}



			} else {
				returnModel.setResult(false);
				returnModel.setReason(obj.getString("errmsg"));
				returnModel.setDatum(null);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			returnModel.setResult(false);
			returnModel.setReason(e.getMessage());
		}

		return returnModel;
	}

	@Override
	public void save(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		dao.save("XCXUserManagerMapper.save", pd);
	}

	@Override
	public void delete(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		dao.delete("XCXUserManagerMapper.delete", pd);
	}

	@Override
	public void edit(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		dao.update("XCXUserManagerMapper.edit", pd);
	}

	@Override
	public PageData findById(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		return (PageData) dao.findForObject("XCXUserManagerMapper.findById", pd);
	}

	@Override
	public void saveUserInfor(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		boolean isDoctor = Boolean.valueOf(pd.get("ISDOCTOR").toString());
		pd.put("3TDSESSION", pd.getString("AccessToken"));
		PageData item = sessionManagerService.findById(pd);
		pd.put("OPENID", item.getString("OPENID"));

		// 更新图像
		PageData appUser = this.findById(item);
		appUser.put("PIC", pd.getString("PIC"));
		

		if (isDoctor) {

			appUser.put("USERTYPE", "2");
			this.edit(appUser);
			// 为医生添加后台用户
		
			String dockey = UuidUtil.get32UUID();
			pd.put("USER_ID", dockey); // ID 主键
			pd.put("ROLE_ID", "3");
			pd.put("LAST_LOGIN", ""); // 最后登录时间
			pd.put("IP", ""); // IP
			pd.put("STATUS", "1"); // 状态为禁用
			pd.put("SKIN", "default");
			pd.put("RIGHTS", "");
			pd.put("BZ", "doctor");
			pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), "123456").toString()); // 密码加密
			if (null == userService.findByUsername(pd)) { // 判断用户名是否存在
				userService.saveU(pd); // 执行保存
			} else {
				throw new Exception("用户名已存在！");
			}

			pd.put("DOCTOR_ID", UuidUtil.get32UUID());
			pd.put("RCDSTS", "A");
			pd.put("USER_ID", dockey);

			this.doctorManager.save(pd);

		} else {
			
			appUser.put("USERTYPE", "1");
			this.edit(appUser);
			
			if (null == normalUser.findById(pd)) {
				pd.put("UID", UuidUtil.get32UUID());
				pd.put("VIP", "N");
				normalUser.save(pd);
			}
		}
	}

	@Override
	public PageData getUserInfor(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		String usertype = pd.getString("UserType").toString();
		String AccessToken = pd.getString("AccessToken");
		pd.put("3TDSESSION", AccessToken);
		
		PageData sessionitem = sessionManagerService.findById(pd);
		
		PageData result = null;
		
		if("1".equals(usertype)){
			result = this.normalUser.findById(sessionitem);
			result.put("ISDOCTOR", false);
		} else if("2".equals(usertype)){
			result = doctorManager.findByOpenId(sessionitem);
			result.put("ISDOCTOR", true);
			
		}
		
		return result;
	}

}
